package ca.jsbr.as2js_lib.utils 
{
	import ca.jsbr.as2js_lib.event.EventDispatcher;
	import ca.jsbr.as2js_lib.event.RequestEvent;
	import ca.jsbr.as2js_lib.utils.generic.PathUtils;
	import flash.events.Event;
	import flash.utils.Dictionary;
	import js.document;
	import js.JSON;
	import js.Node;
	import js.window;
	import js.XMLDocument;
	import js.XMLHttpRequest;
	/**
	 * ...
	 * @author jsbr [me@jsbr.ca]
	 * 
	 * 
	 *  
	 * https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest?redirectlocale=en-US&redirectslug=Using_XMLHttpRequest#Monitoring_progress
loadstart 	Progress has begun. 			Once. 			First.
progress 	In progress. 					Zero or more. 	After loadstart has been dispatched. (evt.loaded / evt.total)
error 		Progression failed. 			Zero or once. 	After the last progress has been dispatched, or after loadstart has been dispatched if progress has not been dispatched.
abort 		Progression is terminated. 		Zero or once.
load 		Progression is successful. 		Zero or once.
loadend 	Progress has stopped. 			Once. 			After one of error, abort, or load has been dispatched. 
	 * 
	 */
	
	 
	 
	public class DataLoader extends EventDispatcher 
	{
		
		static public const STATE_UNSENT:int = 0;
		static public const STATE_OPENED:int = 1;
		static public const STATE_HEADERS_RECEIVED:int = 2;
		static public const STATE_LOADING:int = 3;
		static public const STATE_DONE:int = 4;
		
		
		public static const GET:String = "get";
		public static const POST:String = "post";
		
		public static const XML_TYPE:String='xml';
		public static const TEXT_TYPE:String='plain';
		public static const JSON_TYPE:String='json';
		
		private var _xmlRequest:XMLHttpRequest;
		private var _method:String;
		private var _params:Dictionary;
		private var _path:String;
		private var _type:String = XML_TYPE;
		private var _mimeType:String = XML_TYPE;
		
		public function DataLoader(type:String=null) 
		{
			_type = type;
			
			_xmlRequest = new XMLHttpRequest();
			//_xmlRequest.load = onLoadComplete;
			_xmlRequest.onload = onLoadComplete;
			_xmlRequest.onreadystatechange = onStateChange;
			/*_xmlRequest.addEventListener("load", onLoadComplete);
			_xmlRequest.addEventListener("error", onErrorComplete);
			_xmlRequest.addEventListener("readystatechange", onStateChange);*/
			_params = new Dictionary();
		}
		
		private function checkMimeType():String
		{
			if(!_type && _path)
			{
				if (_path.indexOf(".xml")==_path.length-4){
					_type = XML_TYPE;
				}
				if (_path.indexOf(".json")==_path.length-5){
					_type = JSON_TYPE;
				}
			}
			_mimeType = 'text/plain';
			switch (_type) 
			{
				case XML_TYPE:
					_mimeType = "text/XML";
				break;
				case TEXT_TYPE:
					_mimeType = "text/plain";
				break;
				case JSON_TYPE:
					_mimeType = "application/json";
				break;
			}
			return _mimeType;
		}
		
		private function onStateChange(e:Event):void 
		{
			dispatchEvent(new RequestEvent(RequestEvent.STATE_CHANGE,_xmlRequest.readyState,0));
		}
		
		private function onErrorComplete(e:Event):void 
		{
			
		}
		
		private function onLoadComplete(e:Event):void 
		{
			dispatchEvent(new RequestEvent(RequestEvent.COMPLETE,_xmlRequest.readyState,0));
		}
		
		public function addParam(key:String, value:String):void
		{
			_params[key] = value;
		}
		
		public function load(path:String, params:Dictionary=null, method:String = GET)
		{
			_path = path;
			_method = method;
			
			var paramsstr = "";
			
			for (var ind:String in params){
				paramsstr+=ind+'='+params[ind]+'&';
			}
			for (ind in _params){
				paramsstr+=ind+'='+_params[ind]+'&';
			}

			
			_xmlRequest.open(_method, _path, true);
			checkMimeType();
			var header:String = _mimeType;
			if(method=='post' || method=='POST')
				header += "application/x-www-form-urlencoded; charset=UTF-8;";
			if(header!="")
				_xmlRequest.setRequestHeader("Content-Type", header);
			_xmlRequest.send(paramsstr);
		}
		
		public function getJSON():Object
		{
			if(window["JSON"])
				return JSON.parse(_xmlRequest.responseText);
			else
			{
				try
				{
					this._data = eval("new Object("+_xmlRequest.responseText+")");
				}
				catch(e){
					//jslib.output.trow("Error: JSON Parse error in file "+this._url+"; "+e.message)
					trow(e);
				}
			}
			return _xmlRequest.responseXML;
		}
		
		public function getXmlDocument():XMLDocument
		{
			return _xmlRequest.responseXML;
		}
		
		public function getXmlNode():Node
		{
			if (_xmlRequest.responseXML.childNodes[0].nodeName == "xml")
				return _xmlRequest.responseXML.childNodes[1]
			return _xmlRequest.responseXML.childNodes[0];
		}
		
		public function getText():String
		{
			return _xmlRequest.responseText;
		}
		
		public function get method():String 
		{
			return _method;
		}
		
		public function set method(value:String):void 
		{
			_method = value;
		}		
		
		public function get path():String 
		{
			return _path;
		}
		
	}

}